package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetSmscodeParam(param map[string]interface{}, order string) (*models_main.Smscode, error) {
	fName := "GetSmscodeParam"
	o := &models_main.Smscode{}
	table := mysql.GetRTable(&models_main.Smscode{})
	mysql.Condition(table, param, "", order, 0, 0)
	err := table.Order("id asc").
		Limit(1).
		Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetSmscodeCount(param map[string]interface{}) (int64, error) {
	fName := "GetSmscodeCount"
	var o int64
	table := mysql.GetRTable(&models_main.Smscode{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Count(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func UpdateSmscode(smscode *models_main.Smscode) error {
	fName := "UpdateSmscode"
	err := global.GetX().Where("id = ?", smscode.Id).Select("status").Updates(smscode).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func InsertSmscode(session *gorm.DB, smscode *models_main.Smscode) error {
	fName := "InsertSmscode"
	if session == nil {
		session = global.GetX()
	}
	err := session.Create(smscode).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
